//
//  UIImageExtension.swift
//  SimpleAlert
//
//  Created by Kyohei Ito on 2019/06/15.
//  Copyright © 2019 kyohei_ito. All rights reserved.
//

import UIKit

extension UIImage {
    public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        let context = UIGraphicsGetCurrentContext()
        let rect = CGRect(origin: .zero, size: size)
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        
        defer {
            UIGraphicsEndImageContext()
        }
        
        guard let image = UIGraphicsGetImageFromCurrentImageContext(), let data = image.pngData() else { return nil }
        self.init(data: data, scale: image.scale)
    }
    
    /// 为图片设置圆角，生成新的图片
    public func addRadius(_ radius: CGFloat) -> UIImage? {
        guard radius > 0 else {
            return self
        }
        
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        let context = UIGraphicsGetCurrentContext()
        
        let rect = CGRect(origin: .zero, size: self.size)
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius))

        context?.addPath(path.cgPath)
        context?.clip()
        self.draw(in: rect)
        context?.drawPath(using: .fillStroke)
        
        defer {
            UIGraphicsEndImageContext()
        }
        
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
        return image

    }
    
    public func transparentColor(colorMasking:[CGFloat]) -> UIImage? {
        if let rawImageRef = self.cgImage {
            UIGraphicsBeginImageContext(self.size)
            if let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking) {
                let context: CGContext = UIGraphicsGetCurrentContext()!
                context.translateBy(x: 0.0, y: self.size.height)
                context.scaleBy(x: 1.0, y: -1.0)
                context.draw(maskedImageRef, in: CGRect(x:0, y:0, width:self.size.width, height:self.size.height))
                let result = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                return result
            }
        }
        return nil
    }


    public func grayImage() -> UIImage?{
       UIGraphicsBeginImageContext(self.size)
       let colorSpace = CGColorSpaceCreateDeviceGray()
       let context = CGContext(data: nil , width: Int(self.size.width), height: Int(self.size.height),bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.none.rawValue)
       context?.draw(self.cgImage!, in: CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height))
       let cgImage = context!.makeImage()
       let grayImage = UIImage(cgImage: cgImage!, scale: self.scale, orientation: self.imageOrientation)
       return grayImage
    }
    
    public func imageWithTintColor(color : UIColor) -> UIImage {
        
        UIGraphicsBeginImageContext(self.size)
        color.setFill()
        let bounds = CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height)
        UIRectFill(bounds)
        self.draw(in: bounds, blendMode: CGBlendMode.destinationIn, alpha: 1.0)
        
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return tintedImage!
    }
    ///压缩图片到指定大小
    public func compressImage( maxSize: Int) -> Data? {
        var compression: CGFloat = 1.0
        let maxCompression: CGFloat = 0.1
        let targetSize = CGSize(width: 1024, height: 1024)
        //指定尺寸
//        let scale = UIScreen.main.scale //根据设备屏幕缩放比例调整尺寸
        var imageData = self.jpegData(compressionQuality: compression)
        var imageSize = imageData?.count ?? 0
        var sizeExceeded = imageSize > maxSize
        while sizeExceeded && compression > maxCompression {
            compression -= 0.1
            imageData = self.jpegData(compressionQuality: compression)
            imageSize = imageData?.count ?? 0
            sizeExceeded = imageSize > maxSize
        }
        if let imageSource = CGImageSourceCreateWithData(imageData! as CFData, nil) {
            
            let options: [CFString: Any] = [
                kCGImageSourceThumbnailMaxPixelSize: max(targetSize.width, targetSize.height) * 1.0,
                kCGImageSourceCreateThumbnailFromImageAlways: true,
                kCGImageSourceCreateThumbnailWithTransform: true ]
            if let scaledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary) {
                if let scaledImageData = UIImage(cgImage: scaledImage).jpegData(compressionQuality: compression) {
                    imageData = scaledImageData
                }
            }
        }
        return imageData
    }

}
